import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/enum/menu_type.dart';
import 'package:gt_flutter_admin/services/api_service.dart';
import 'package:gt_flutter_admin/utils/toast_utils.dart';

import '../../../models/menu.dart';
import '../../../models/page.dart' as gt_page;

class MenuUpdateController extends GetxController with StateMixin {
  // 控制器
  final Rx<gt_page.Page> menuPage = gt_page.Page().obs;

  // 选择控件
  num? parentId;
  final RxString parentName = ''.obs;

  final RxString type = MenuType.MENU.value.obs;

  // 文本控件
  final TextEditingController menuNameText = TextEditingController();
  final TextEditingController pathText = TextEditingController();
  final TextEditingController permsText = TextEditingController();
  final TextEditingController iconText = TextEditingController();
  final TextEditingController orderNumText = TextEditingController();

  @override
  void onReady() async {
    super.onReady();

    // 初始化菜单选择
    menuPage.value = await listMenu();

    Menu? menu = Get.rootDelegate.arguments();
    if (menu != null) {
      menuNameText.text = menu.menuName;

      if (menu.parentId != 0) {
        Menu parentMenu = await getMenu(menu.parentId);
        parentId = parentMenu.id;
        parentName.value = parentMenu.menuName;
      }

      pathText.text = menu.path ?? '';
      permsText.text = menu.perms ?? '';
      iconText.text = menu.icon ?? '';
      type.value = MenuType.values[int.parse(menu.type)].value;
      orderNumText.text = '${menu.orderNum}';
    }
  }

  /// 提交表单
  void onSubmit() {
    Menu menu = Get.rootDelegate.arguments();

    Map<String, dynamic> data = {
      'icon': iconText.text,
      'id': menu.id,
      'menuName': menuNameText.text,
      'orderNum': orderNumText.text,
      'parentId': parentId,
      'path': pathText.text,
      'perms': permsText.text,
      'type': MenuType.getIndex(type.value),
    };

    updateMenu(data).then((value) => ToastUtils.success('编辑成功'));
    Get.rootDelegate.toNamed(Routes.USER);
  }
}
